package com.studentmanagement.ui;

import com.studentmanagement.model.Course;
import com.studentmanagement.model.Teacher;
import com.studentmanagement.service.CourseService;
import com.studentmanagement.service.TeacherService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;

public class CourseEditDialog extends JDialog {
    private JTextField courseCodeField;
    private JTextField nameField;
    private JTextField creditsField;
    private JComboBox<String> teacherComboBox;
    private JTextField departmentField;
    private JTextField descriptionField;
    private JTextField capacityField;
    private JTextField scheduleField;
    private JTextField classroomField;
    private JButton saveButton;
    private JButton cancelButton;
    private boolean saved = false;
    private CourseService courseService = new CourseService();
    private TeacherService teacherService = new TeacherService();
    private Course course;
    private List<Teacher> teacherList;

    public CourseEditDialog(Course course) {
        this.course = course;
        setTitle(course == null ? "新增课程" : "编辑课程");
        setModal(true);
        loadTeachers();
        initComponents();
        setupLayout();
        setupListeners();
        if (course != null) {
            fillForm(course);
        }
        pack();
        setLocationRelativeTo(null);
    }

    private void loadTeachers() {
        teacherList = teacherService.getAllTeachers();
    }

    private void initComponents() {
        courseCodeField = new JTextField(15);
        nameField = new JTextField(15);
        creditsField = new JTextField(5);
        
        // 创建教师下拉框
        String[] teacherNames = new String[teacherList.size() + 1];
        teacherNames[0] = "-- 请选择教师 --";
        for (int i = 0; i < teacherList.size(); i++) {
            teacherNames[i + 1] = teacherList.get(i).getName() + " (" + teacherList.get(i).getTeacherId() + ")";
        }
        teacherComboBox = new JComboBox<>(teacherNames);
        
        departmentField = new JTextField(15);
        descriptionField = new JTextField(20);
        capacityField = new JTextField(5);
        scheduleField = new JTextField(15);
        classroomField = new JTextField(15);
        saveButton = new JButton("保存");
        cancelButton = new JButton("取消");
    }

    private void setupLayout() {
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(6, 6, 6, 6);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        int row = 0;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("课程代码:"), gbc);
        gbc.gridx = 1; formPanel.add(courseCodeField, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("课程名称:"), gbc);
        gbc.gridx = 1; formPanel.add(nameField, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("学分:"), gbc);
        gbc.gridx = 1; formPanel.add(creditsField, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("授课教师:"), gbc);
        gbc.gridx = 1; formPanel.add(teacherComboBox, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("开课院系:"), gbc);
        gbc.gridx = 1; formPanel.add(departmentField, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("课程描述:"), gbc);
        gbc.gridx = 1; formPanel.add(descriptionField, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("课程容量:"), gbc);
        gbc.gridx = 1; formPanel.add(capacityField, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("上课时间:"), gbc);
        gbc.gridx = 1; formPanel.add(scheduleField, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("教室:"), gbc);
        gbc.gridx = 1; formPanel.add(classroomField, gbc); row++;

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        setLayout(new BorderLayout(10, 10));
        add(formPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupListeners() {
        saveButton.addActionListener(this::onSave);
        cancelButton.addActionListener(e -> dispose());
    }

    private void fillForm(Course c) {
        courseCodeField.setText(c.getCourseCode());
        nameField.setText(c.getName());
        creditsField.setText(String.valueOf(c.getCredits()));
        
        // 设置教师选择
        if (c.getTeacherId() != null) {
            for (int i = 0; i < teacherList.size(); i++) {
                if (teacherList.get(i).getId().equals(c.getTeacherId())) {
                    teacherComboBox.setSelectedIndex(i + 1); // +1 因为第一个是默认项
                    break;
                }
            }
        }
        
        departmentField.setText(c.getDepartment());
        descriptionField.setText(c.getDescription());
        capacityField.setText(String.valueOf(c.getCapacity()));
        scheduleField.setText(c.getSchedule());
        classroomField.setText(c.getClassroom());
    }

    private void onSave(ActionEvent e) {
        if (courseCodeField.getText().trim().isEmpty() || nameField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "课程代码和名称不能为空！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 验证学分格式
        int credits;
        try {
            credits = Integer.parseInt(creditsField.getText().trim());
            if (credits < 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "学分必须是正整数！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 验证容量格式
        int capacity;
        try {
            capacity = Integer.parseInt(capacityField.getText().trim());
            if (capacity < 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "容量必须是正整数！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (course == null) {
            course = new Course();
        }
        
        course.setCourseCode(courseCodeField.getText().trim());
        course.setName(nameField.getText().trim());
        course.setCredits(credits);
        
        // 获取选中的教师ID
        int teacherIndex = teacherComboBox.getSelectedIndex();
        if (teacherIndex > 0) { // 0是默认选项
            course.setTeacherId(teacherList.get(teacherIndex - 1).getId());
        } else {
            course.setTeacherId(null);
        }
        
        course.setDepartment(departmentField.getText().trim());
        course.setDescription(descriptionField.getText().trim());
        course.setCapacity(capacity);
        course.setSchedule(scheduleField.getText().trim());
        course.setClassroom(classroomField.getText().trim());
        
        boolean success;
        if (course.getId() == null) {
            success = courseService.insertCourse(course);
        } else {
            success = courseService.updateCourse(course);
        }
        
        if (success) {
            saved = true;
            JOptionPane.showMessageDialog(this, "保存成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "保存失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public boolean isSaved() {
        return saved;
    }
} 